package com.dalin.demo.controller;

import com.dalin.demo.pojo.entity.EnrollStudentsRequest;
import com.dalin.demo.pojo.entity.StudentCourse;
import com.dalin.demo.service.StudentCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/studentCourse")
@CrossOrigin(origins = "*")
public class StudentCourseController {

    @Autowired
    private StudentCourseService studentCourseService;

    @PostMapping("/batchAdd")
    public void batchAddStudentCourses(@RequestBody List<StudentCourse> studentCourses) {
        studentCourseService.batchAddStudentCourses(studentCourses);
    }

    @PostMapping("/enrollStudents")
    public ResponseEntity<?> enrollStudentsToCourse(@RequestBody EnrollStudentsRequest request) {
        try {
            List<StudentCourse> studentCourses = request.getStudentIds().stream()
                .map(studentId -> new StudentCourse(request.getCourseId(), studentId))
                .collect(Collectors.toList());
            
            studentCourseService.batchAddStudentCourses(studentCourses);
            return ResponseEntity.ok("Students successfully enrolled to the course");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error enrolling students to the course");
        }
    }

    @GetMapping("/enrolledStudents/{courseId}")
    public ResponseEntity<?> getEnrolledStudents(@PathVariable Long courseId) {
        try {
            List<StudentCourse> enrolledStudents = studentCourseService.getEnrolledStudentsByCourseId(courseId);
            System.out.println(enrolledStudents);
            return ResponseEntity.ok(enrolledStudents);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving enrolled students");
        }
    }

    @DeleteMapping("/delete/{id}")
    public String deleteStudent(@PathVariable Integer id) {
        System.out.println("deleteStudent by id==="+ id);
        studentCourseService.deleteStudent(id);
        return "success";
    }
}